package lyq.spec.edu.practical;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.SystemClock;
import android.util.Log;

import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Date;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MyService extends Service {


    private static final String TAG = "MyService";
    public MyService() {
    }


    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }



    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Log.d("LongRunningService", "executed at " + new Date().
                        toString());
                sendRequestWihtOkhttp();
            }
        }).start();
        AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);
        int anHour =10 * 1000;   // 这是10秒的毫秒数
        long triggerAtTime = SystemClock.elapsedRealtime() + anHour;
        Intent i = new Intent(MyService.this, MyReceiver.class);
        PendingIntent pi = PendingIntent.getBroadcast(MyService.this, 0, i, 0);
        manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtTime, pi);
        return super.onStartCommand(intent, flags, startId);
    }

    /**
     * 发起网络请求
     */
    private void sendRequestWihtOkhttp() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {

                    // 构造客户端，相当于浏览器
                    OkHttpClient client = new OkHttpClient();


                    // 构造请求，相当于在浏览器里输入地址
                    Request request = new Request
                            .Builder()
                            .url("http://www.yyjsx.xyz/api/iot/readHumiture")
                            .build();
                    // 发送请求，相当于在浏览器按回车
                    Response response = client.newCall(request).execute();
                    // 更新ListView
                    String body = response.body().string();
                    Log.d(TAG, body);
                    parseJson(body);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

   private void parseJson(String jsonStr) {
        try {
            JSONObject jobj = new JSONObject(jsonStr);

            String dataStr  = jobj.getString("data");

            Gson gson = new Gson();
            Humiture humiture = gson.fromJson(dataStr, Humiture.class);
            String t = humiture.getTemperature();
            String h = humiture.getHumidity();
            String ws = "室内温度: "+t+"   ℃\n室内湿度: "+h+"   %";
            /*//传值给strings.xml
            String data = getResources().getString(R.string.data);
            String ws = String.format(data, t, h);*/
            Log.d(TAG, ws);
            //发送广播
            Intent intent=new Intent();
            intent.putExtra("count", ws);
            intent.setAction("lyq.spec.edu.MyService");
            sendBroadcast(intent);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}
